package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 查询工具类
 * @date 2022/11/21 17:57
 */
@Component
@Slf4j
public class CancheClient {
    @Resource
    private  StringRedisTemplate stringRedisTemplate;


    //存入redis
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    //逻辑删除方式存入
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    /**
     * @param id
     * @return com.hmdp.entity.Shop
     * @description 封装店铺查询 解决穿透 雪崩
     * @author 31115
     * @date 2022/11/20 20:55
     */
    public <R, ID> R getQueryWithPassThrough
    (String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //使用redis查询数据
        if (StringUtils.isNotBlank(json)) {
            //不为空 存在 直接返回
            return JSONUtil.toBean(json, type);
        }

        //判断如果redis数据为空则提示用户
        if (json != null) {
            return null;
        }

        R r = dbFallback.apply(id);
        if (r == null) {
            //赋空值 (缓存穿透)
            stringRedisTemplate.opsForValue().set(key, "", time, unit);
            return null;
        }

        //数据库查询出返回数据 并且存入redis
        // 添加随机数 解决雪崩
        Random random = new Random();
        int nextInt = random.nextInt(2) + 1;
        this.set(key, r, time + nextInt, unit);

        return r;
    }


    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * @param id
     * @return com.hmdp.entity.Shop
     * @description 逻辑过期 查询 解决击穿
     * @author 31115
     * @date 2022/11/20 23:22
     */
    public <R, ID> R getQueryWithLogicalExpire
    (String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //使用redis查询数据
        if (StringUtils.isBlank(json)) {
            //不存在 返回null
            log.info("key不存在");
            return null;
        }

        //存在 先获取redis中的数据 转为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject jsonData = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(jsonData, type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //还没过期
            return r;
        }

        //过期了
        //获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean lock = tryLock(lockKey);
        if (lock) {
            try {
                //获取锁成功 开线程重建缓存
                CACHE_REBUILD_EXECUTOR.submit(new Runnable() {
                    @Override
                    public void run() {
                        //先查数据库
                        R r1 = dbFallback.apply(id);
                        //插入缓存
                        setWithLogicalExpire(key, r1, time, unit);
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                //释放锁
                unLock(lockKey);
            }
        }

        return r;
    }


    /**
     * @param key
     * @return boolean
     * @description 尝试获取锁 setnx
     * @author 31115
     * @date 2022/11/20 20:51
     */
    public boolean tryLock(String key) {
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(ifAbsent);
    }

    /**
     * @param key
     * @return void
     * @description 释放setnx锁
     * @author 31115
     * @date 2022/11/20 20:54
     */
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
